// 二维码工具专用功能
class QRCodeTool {
    static instance = null;

    static getInstance() {
        if (!QRCodeTool.instance) {
            QRCodeTool.instance = new QRCodeTool();
        }
        return QRCodeTool.instance;
    }

    showToast(message, type = 'info') {
        // 创建toast元素
        const toast = document.createElement('div');
        toast.style.position = 'fixed';
        toast.style.top = '20px';
        toast.style.right = '20px';
        toast.style.padding = '12px 20px';
        toast.style.borderRadius = '4px';
        toast.style.color = 'white';
        toast.style.zIndex = '10000';
        toast.style.fontSize = '14px';
        toast.style.minWidth = '200px';
        toast.style.textAlign = 'center';
        toast.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
        
        // 设置背景颜色基于类型
        const colors = {
            success: '#4caf50',
            warning: '#ff9800',
            error: '#f44336',
            info: '#2196f3'
        };
        toast.style.backgroundColor = colors[type] || colors.info;
        
        toast.textContent = message;
        
        // 添加到页面
        document.body.appendChild(toast);
        
        // 3秒后自动消失
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 1000);
    }
    constructor() {
        this.qrCodes = [];
        this.init();
    }

    init() {
        // 初始化事件监听
        this.bindEvents();
        this.loadPrefixesFromStorage();
    }

    bindEvents() {
        // 输入方式切换标签 - 限制在二维码工具范围内
        const inputTabs = document.querySelectorAll('#qrcode-tool .input-tab');
        inputTabs.forEach(tab => {
            tab.addEventListener('click', (e) => {
                const tabName = e.target.dataset.tab;
                this.switchInputTab(tabName);
            });
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch (e.key) {
                    case 'Enter':
                        e.preventDefault();
                        this.generateQRCodes();
                        break;
                    case 'l':
                        e.preventDefault();
                        this.clearQRCodes();
                        break;
                }
            }
        });

        // 前缀选择事件
        const prefixSelect = document.getElementById('prefix-select');
        if (prefixSelect) {
            prefixSelect.addEventListener('change', (e) => {
                const manualPrefix = document.getElementById('manual-prefix');
                if (manualPrefix ) {
                    manualPrefix.value = e.target.value;
                }
            });
        }

        // 保存按钮事件
        const saveBtn = document.getElementById('save-prefix-btn');
        if (saveBtn) {
            saveBtn.addEventListener('click', () => {
                this.saveCustomPrefix();
            });
        }

        // 管理按钮事件
        const manageBtn = document.getElementById('manage-prefix-btn');
        if (manageBtn) {
            manageBtn.addEventListener('click', () => {
                this.manageCustomPrefixes();
            });
        }
    }

    switchInputTab(tabName) {
        // 更新标签状态 - 限制在二维码工具范围内
        document.querySelectorAll('#qrcode-tool .input-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`#qrcode-tool [data-tab="${tabName}"]`).classList.add('active');

        // 更新内容区域 - 限制在二维码工具范围内
        document.querySelectorAll('#qrcode-tool .input-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tabName}-input`).classList.add('active');
    }

    generateNumbers() {
        const prefix = document.getElementById('prefix').value;
        const digitLength = parseInt(document.getElementById('digit-length').value) || 3;
        const startNum = parseInt(document.getElementById('start-num').value) || 1;
        const endNum = parseInt(document.getElementById('end-num').value) || 10;

        if (startNum > endNum) {
            alert('开始编号必须小于或等于结束编号');
            return;
        }

        const numbers = [];
        for (let i = startNum; i <= endNum; i++) {
            const paddedNumber = String(i).padStart(digitLength, '0');
            numbers.push(prefix + paddedNumber);
        }

        document.getElementById('qrcode-data-manual').value = numbers.join('\n');
        
        // 直接生成二维码，不再切换标签
        this.generateQRCodes();
    }

    generateQRCodes() {
        const data = this.getInputData();
        if (!data || data.length === 0) {
            alert('请输入数据');
            return;
        }

        const size = parseInt(document.getElementById('qr-size').value) || 200;
        const errorLevel = document.getElementById('qr-error-level').value;

        this.clearQRCodes();

        data.forEach((item, index) => {
            if (item.trim()) {
                this.createQRCode(item.trim(), size, errorLevel, index);
            }
        });
    }

    getInputData() {
        const activeTab = document.querySelector('.input-tab.active').dataset.tab;
        let data = [];

        if (activeTab === 'manual') {
            const text = document.getElementById('qrcode-data-manual').value;
            const manualPrefix = document.getElementById('manual-prefix')?.value || '';
            data = text.split('\n')
                .filter(line => line.trim())
                .map(line => manualPrefix + line.trim());
        } else if (activeTab === 'auto') {
            // 自动生成模式下，直接根据参数生成数据
            const prefix = document.getElementById('prefix').value;
            const digitLength = parseInt(document.getElementById('digit-length').value) || 3;
            const startNum = parseInt(document.getElementById('start-num').value) || 1;
            const endNum = parseInt(document.getElementById('end-num').value) || 10;

            if (startNum <= endNum) {
                for (let i = startNum; i <= endNum; i++) {
                    const paddedNumber = String(i).padStart(digitLength, '0');
                    data.push(prefix + paddedNumber);
                }
            }
        }

        return data;
    }

    createQRCode(text, size, errorLevel, index) {
        const resultsDiv = document.getElementById('qrcode-results');
        const qrItem = document.createElement('div');
        qrItem.className = 'qr-item';
        qrItem.style.animationDelay = `${index * 0.1}s`;

        const qrCodeDiv = document.createElement('div');
        qrCodeDiv.className = 'qr-code';
        qrCodeDiv.id = `qr-${index}`;

        const qrLabel = document.createElement('div');
        qrLabel.className = 'qr-label';
        qrLabel.textContent = text;

        const downloadBtn = document.createElement('button');
        downloadBtn.className = 'download-btn';
        downloadBtn.textContent = '下载';
        downloadBtn.onclick = () => this.downloadQRCode(index, text);

        qrItem.appendChild(qrCodeDiv);
        qrItem.appendChild(qrLabel);
        qrItem.appendChild(downloadBtn);
        resultsDiv.appendChild(qrItem);

        try {
            // 根据主题设置二维码颜色
            const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark';
            const qr = new QRCode(qrCodeDiv, {
                text: text,
                width: size,
                height: size,
                colorDark: isDarkMode ? '#ffffff' : '#000000',
                colorLight: isDarkMode ? '#2d2d2d' : '#ffffff',
                correctLevel: this.getErrorLevel(errorLevel)
            });

            this.qrCodes.push({
                element: qrCodeDiv,
                text: text,
                qr: qr
            });
        } catch (error) {
            console.error('生成二维码失败:', error);
            qrItem.innerHTML = `
                <div style="color: #ff6b6b; padding: 20px; text-align: center;">
                    生成失败: ${text.substring(0, 20)}...
                </div>
            `;
        }
    }

    getErrorLevel(level) {
        switch (level) {
            case 'L': return QRCode.CorrectLevel.L;
            case 'M': return QRCode.CorrectLevel.M;
            case 'Q': return QRCode.CorrectLevel.Q;
            case 'H': return QRCode.CorrectLevel.H;
            default: return QRCode.CorrectLevel.M;
        }
    }

    downloadQRCode(index, text) {
        const qrElement = document.getElementById(`qr-${index}`);
        if (!qrElement) return;

        const canvas = qrElement.querySelector('canvas');
        if (!canvas) return;

        const link = document.createElement('a');
        link.download = `qrcode-${text.replace(/[^a-zA-Z0-9]/g, '_')}.png`;
        link.href = canvas.toDataURL();
        link.click();
    }

    loadPrefixesFromStorage() {
        // 从localStorage加载自定义前缀
        const storedPrefixes = localStorage.getItem('qrcode_custom_prefixes');
        this.customPrefixes = storedPrefixes ? JSON.parse(storedPrefixes) : [];
        
        // 只使用用户自定义前缀
        this.allPrefixes = [...this.customPrefixes];
        this.populatePrefixSelect(this.allPrefixes, "");
    }

    populatePrefixSelect(prefixes, defaultPrefix) {
        const prefixSelect = document.getElementById('prefix-select');
        if (!prefixSelect) return;

        // 清空现有选项
        prefixSelect.innerHTML = '<option value="">选择已保存前缀</option>';
        
        // 添加自定义前缀选项
        if (this.customPrefixes.length > 0) {
            const customGroup = document.createElement('optgroup');
            customGroup.label = "已保存前缀";
            
            this.customPrefixes.forEach(prefix => {
                const option = document.createElement('option');
                option.value = prefix.value;
                option.textContent = `${prefix.name} (${prefix.value})`;
                customGroup.appendChild(option);
            });
            prefixSelect.appendChild(customGroup);
        }

        // 设置默认前缀
        const manualPrefix = document.getElementById('manual-prefix');
        if (manualPrefix && defaultPrefix) {
            manualPrefix.value = defaultPrefix;
        }
    }

    saveCustomPrefix() {
        const manualPrefix = document.getElementById('manual-prefix');
        const customPrefix = manualPrefix.value.trim();
        
        if (!customPrefix) {
            this.showToast('请输入自定义前缀', 'warning');
            return;
        }

        // 检查是否已存在（包括默认前缀和自定义前缀）
        const exists = this.allPrefixes.some(p => p.value === customPrefix);
        if (exists) {
            this.showToast('该前缀已存在', 'warning');
            return;
        }

        // 使用自定义模态对话框获取前缀名称
        this.showPrefixNameDialog(customPrefix);
    }

    showPrefixNameDialog(customPrefix) {
        // 创建模态对话框
        const modal = document.createElement('div');
        modal.style.position = 'fixed';
        modal.style.top = '50%';
        modal.style.left = '50%';
        modal.style.transform = 'translate(-50%, -50%)';
        modal.style.backgroundColor = 'white';
        modal.style.padding = '20px';
        modal.style.border = '2px solid #ccc';
        modal.style.borderRadius = '8px';
        modal.style.zIndex = '1000';
        modal.style.minWidth = '300px';

        // 添加标题
        const title = document.createElement('h3');
        title.textContent = '输入前缀名称';
        title.style.marginTop = '0';
        modal.appendChild(title);

        // 添加说明
        const description = document.createElement('p');
        description.textContent = '请输入自定义前缀的名称（例如：产品序列号）:';
        description.style.margin = '10px 0';
        modal.appendChild(description);

        // 添加输入框
        const nameInput = document.createElement('input');
        nameInput.type = 'text';
        nameInput.value = `前缀名称`;
        nameInput.style.width = '100%';
        nameInput.style.padding = '8px';
        nameInput.style.border = '1px solid #ddd';
        nameInput.style.borderRadius = '4px';
        nameInput.style.marginBottom = '15px';
        modal.appendChild(nameInput);

        // 添加按钮容器
        const buttonContainer = document.createElement('div');
        buttonContainer.style.display = 'flex';
        buttonContainer.style.gap = '10px';
        buttonContainer.style.justifyContent = 'flex-end';

        // 添加取消按钮
        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = '取消';
        cancelBtn.className = 'secondary-btn';
        cancelBtn.onclick = () => {
            modal.remove();
            overlay.remove();
        };
        buttonContainer.appendChild(cancelBtn);

        // 添加确定按钮
        const confirmBtn = document.createElement('button');
        confirmBtn.textContent = '确定';
        confirmBtn.className = 'primary-btn';
        confirmBtn.onclick = () => {
            const prefixName = nameInput.value.trim();
            if (!prefixName) {
                this.showToast('请输入有效的名称', 'warning');
                return;
            }

            // 创建新的自定义前缀
            const newPrefix = {
                name: prefixName,
                value: customPrefix,
                description: "用户自定义前缀",
                isCustom: true
            };

            // 添加到自定义前缀列表
            this.customPrefixes.push(newPrefix);
            this.allPrefixes.push(newPrefix);

            // 保存到localStorage
            localStorage.setItem('qrcode_custom_prefixes', JSON.stringify(this.customPrefixes));

            // 重新填充下拉框
            this.populatePrefixSelect(this.allPrefixes, "");
            
            this.showToast(`前缀 "${prefixName}" 已保存`, 'success');
            
            // 清空输入框
            const manualPrefix = document.getElementById('manual-prefix');
            manualPrefix.value = '';

            // 移除对话框
            modal.remove();
            overlay.remove();
        };
        buttonContainer.appendChild(confirmBtn);

        modal.appendChild(buttonContainer);

        // 添加遮罩层
        const overlay = document.createElement('div');
        overlay.style.position = 'fixed';
        overlay.style.top = '0';
        overlay.style.left = '0';
        overlay.style.width = '100%';
        overlay.style.height = '100%';
        overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
        overlay.style.zIndex = '999';

        // 添加到页面
        document.body.appendChild(overlay);
        document.body.appendChild(modal);

        // 自动聚焦到输入框
        nameInput.focus();
        nameInput.select();
    }

    manageCustomPrefixes() {
        if (this.customPrefixes.length === 0) {
            this.showToast('暂无自定义前缀', 'info');
            return;
        }

        // 创建管理对话框
        const modal = document.createElement('div');
        modal.style.position = 'fixed';
        modal.style.top = '50%';
        modal.style.left = '50%';
        modal.style.transform = 'translate(-50%, -50%)';
        modal.style.backgroundColor = 'white';
        modal.style.padding = '20px';
        modal.style.border = '2px solid #ccc';
        modal.style.borderRadius = '8px';
        modal.style.zIndex = '1000';
        modal.style.maxWidth = '500px';
        modal.style.maxHeight = '80vh';
        modal.style.overflow = 'auto';

        // 添加标题
        const title = document.createElement('h3');
        title.textContent = '管理自定义前缀';
        title.style.marginTop = '0';
        modal.appendChild(title);

        // 添加前缀列表
        const list = document.createElement('ul');
        list.style.listStyle = 'none';
        list.style.padding = '0';

        this.customPrefixes.forEach((prefix, index) => {
            const listItem = document.createElement('li');
            listItem.style.display = 'flex';
            listItem.style.justifyContent = 'space-between';
            listItem.style.alignItems = 'center';
            listItem.style.marginBottom = '10px';
            listItem.style.padding = '8px';
            listItem.style.backgroundColor = '#f5f5f5';
            listItem.style.borderRadius = '4px';

            const prefixInfo = document.createElement('span');
            prefixInfo.textContent = `${prefix.name} (${prefix.value})`;

            const deleteBtn = document.createElement('button');
            deleteBtn.textContent = '删除';
            deleteBtn.style.backgroundColor = '#ff4444';
            deleteBtn.style.color = 'white';
            deleteBtn.style.border = 'none';
            deleteBtn.style.padding = '5px 10px';
            deleteBtn.style.borderRadius = '3px';
            deleteBtn.style.cursor = 'pointer';
            deleteBtn.onclick = () => {
                if (confirm(`确定要删除前缀 "${prefix.value}" 吗？`)) {
                    this.customPrefixes.splice(index, 1);
                    localStorage.setItem('qrcode_custom_prefixes', JSON.stringify(this.customPrefixes));
                    this.loadPrefixesFromStorage();
                    modal.remove();
                    this.showToast('前缀已删除', 'success');
                }
            };

            listItem.appendChild(prefixInfo);
            listItem.appendChild(deleteBtn);
            list.appendChild(listItem);
        });

        modal.appendChild(list);

        // 添加批量删除按钮
        const deleteAllBtn = document.createElement('button');
        deleteAllBtn.textContent = '删除所有自定义前缀';
        deleteAllBtn.style.backgroundColor = '#ff6b6b';
        deleteAllBtn.style.color = 'white';
        deleteAllBtn.style.border = 'none';
        deleteAllBtn.style.padding = '10px 15px';
        deleteAllBtn.style.borderRadius = '4px';
        deleteAllBtn.style.cursor = 'pointer';
        deleteAllBtn.style.marginTop = '15px';
        deleteAllBtn.style.width = '100%';
        deleteAllBtn.onclick = () => {
            if (confirm('确定要删除所有自定义前缀吗？')) {
                this.customPrefixes = [];
                localStorage.removeItem('qrcode_custom_prefixes');
                this.loadPrefixesFromStorage();
                    modal.remove();
                    this.showToast('所有自定义前缀已删除', 'success');
            }
        };

        modal.appendChild(deleteAllBtn);

        // 添加关闭按钮
        const closeBtn = document.createElement('button');
        closeBtn.textContent = '关闭';
        closeBtn.style.backgroundColor = '#666';
        closeBtn.style.color = 'white';
        closeBtn.style.border = 'none';
        closeBtn.style.padding = '10px 15px';
        closeBtn.style.borderRadius = '4px';
        closeBtn.style.cursor = 'pointer';
        closeBtn.style.marginTop = '10px';
        closeBtn.style.width = '100%';
        closeBtn.onclick = () => modal.remove();

        modal.appendChild(closeBtn);

        // 添加遮罩层
        const overlay = document.createElement('div');
        overlay.style.position = 'fixed';
        overlay.style.top = '0';
        overlay.style.left = '0';
        overlay.style.width = '100%';
        overlay.style.height = '100%';
        overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
        overlay.style.zIndex = '999';
        overlay.onclick = () => {
            modal.remove();
            overlay.remove();
        };

        // 添加到页面
        document.body.appendChild(overlay);
        document.body.appendChild(modal);
    }

    async downloadAsZip() {
        if (this.qrCodes.length === 0) {
            alert('请先生成二维码');
            return;
        }

        try {
            // 动态加载JSZip库
            if (typeof JSZip === 'undefined') {
                await this.loadJSZip();
            }

            const zip = new JSZip();
            const folder = zip.folder('qrcodes');

            // 收集所有二维码图片
            for (let i = 0; i < this.qrCodes.length; i++) {
                const qr = this.qrCodes[i];
                const canvas = qr.element.querySelector('canvas');
                if (canvas) {
                    const filename = `qrcode-${i + 1}-${qr.text.replace(/[^a-zA-Z0-9]/g, '_').substring(0, 50)}.png`;
                    
                    // 将canvas转换为blob
                    const blob = await new Promise(resolve => {
                        canvas.toBlob(resolve, 'image/png');
                    });
                    
                    if (blob) {
                        folder.file(filename, blob);
                    }
                }
            }

            // 生成ZIP文件并下载
            const content = await zip.generateAsync({type: 'blob'});
            const link = document.createElement('a');
            link.href = URL.createObjectURL(content);
            link.download = `qrcodes_${new Date().toISOString().slice(0, 10)}.zip`;
            link.click();

            // 清理URL对象
            setTimeout(() => {
                URL.revokeObjectURL(link.href);
            }, 1000);

        } catch (error) {
            console.error('下载ZIP失败:', error);
            alert('下载失败，请重试');
        }
    }

    loadJSZip() {
        return new Promise((resolve, reject) => {
            if (typeof JSZip !== 'undefined') {
                resolve();
                return;
            }

            const script = document.createElement('script');
            script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js';
            script.onload = () => {
                console.log('JSZip loaded successfully');
                resolve();
            };
            script.onerror = () => {
                console.error('Failed to load JSZip');
                reject(new Error('无法加载JSZip库，请检查网络连接'));
            };
            document.head.appendChild(script);
        });
    }

    clearQRCodes() {
        const resultsDiv = document.getElementById('qrcode-results');
        resultsDiv.innerHTML = '';
        this.qrCodes = [];
    }
}

// 全局函数，供HTML调用
function generateNumbers() {
    QRCodeTool.getInstance().generateNumbers();
}

function generateQRCodes() {
    QRCodeTool.getInstance().generateQRCodes();
}

function clearQRCodes() {
    QRCodeTool.getInstance().clearQRCodes();
}

function downloadAsZip() {
    QRCodeTool.getInstance().downloadAsZip();
}

function clearManualInput() {
    document.getElementById('qrcode-data-manual').value = '';
    const mp = document.getElementById('manual-prefix');
    if (mp) mp.value = '';
}

// 初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        QRCodeTool.getInstance();
    });
} else {
    QRCodeTool.getInstance();
}